package org.jash.learnmvp.news;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.jash.learnmvp.R;
import org.jash.learnmvp.entity.NewsEntity;
import org.jash.learnmvp.entity.NewsPageEntity;

import java.util.ArrayList;
import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
    private List<NewsPageEntity.DataBean.RecordsBean> data = new ArrayList<>();
    private OnItemClickListener listener;

    @Override
    public int getItemViewType(int position) {
        return position % 2 == 0 ? R.layout.item_news : R.layout.item_news2;
    }

    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new NewsViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
        NewsPageEntity.DataBean.RecordsBean d = data.get(position);
        holder.title.setText(d.getTitle());
        holder.time.setText(d.getCreateTime());
        Glide.with(holder.icon)
                .load(d.getImgurl())
                .into(holder.icon);
        if (listener != null) {
            holder.itemView.setOnClickListener(v -> listener.onItemClick(d));
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    public void addAll(List<NewsPageEntity.DataBean.RecordsBean> list) {
        int size = data.size();
        data.addAll(list);
        notifyItemRangeInserted(size, list.size());
    }
    public void clear() {
        int size = data.size();
        data.clear();
        notifyItemRangeRemoved(0, size);
    }

    public void setListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(NewsPageEntity.DataBean.RecordsBean bean);
    }
    public static class NewsViewHolder extends RecyclerView.ViewHolder {
        private ImageView icon;
        private TextView title;
        private TextView time;
        public NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            title = itemView.findViewById(R.id.title);
            time = itemView.findViewById(R.id.time);
        }
    }
}
